package com.lockmem.ctrl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.lockmem.Conf.ConfHelper;
import com.lockmem.Conf.ConfKey;
import com.lockmem.Conf.ConfValue;
import com.lockmem.DB.DBHelper;
import com.lockmem.DB.Ebbinghaus;
import com.lockmem.DB.ResNameNumPair;
import com.lockmem.DB.Row;
import com.lockmem.DB.RowEnglish;
import com.lockmem.DB.RowUserData;
import com.lockmem.constants.Constants;
import com.lockmem.study.ChoiceQuestion;

import android.R.integer;
import android.R.string;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class CtrlService extends Service {
	private DBHelper dbhelper;
	private ConfHelper confhelper;
	private SharedPreferences ConfSharePre = null;
	private final IBinder binder = new MyBinder();
	private int[] scanTime = { -1, -1 };
	private final static String tag = "CtrlService";
	private String currentTable = null;
	private List<Row> rows = null;

	private String now() {
		return new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
	}

	private String today() {
		return new SimpleDateFormat("yyyyMMdd").format(new Date());
	}

	private int hour() {
		// TODO Auto-generated method stub
		return Integer.valueOf(new SimpleDateFormat("HH").format(new Date()));
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		// showMsg("onBinding");
		Log.v(tag, "service bind");
		return binder;
	}

	public List<Row> getTopRows(String tablename, int count,
			boolean needTestWrong) {
		String now = new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
		currentTable = tablename;
		return rows = dbhelper.getRows(tablename, count, now,
				getConfSharePref().getInt(ConfKey.Order, 3), needTestWrong);
	}

	@Override
	public void onCreate() {
		confhelper = new ConfHelper(this);
		dbhelper = new DBHelper(CtrlService.this);
		// TODO Auto-generated method stub
		// showMsg("onCreating");
		super.onCreate();
	}

	/**
	 * 
	 * @author lee
	 * 
	 */
	public class MyBinder extends Binder {
		public CtrlService getService() {
			return CtrlService.this;
		}

	}

	public RowUserData getUserData(String current_tablename) {
		// TODO Auto-generated method stub
		return dbhelper.getUserData(current_tablename);
	}

	private SharedPreferences getConfSharePref() {
		if (ConfSharePre == null) {
			ConfSharePre = confhelper.getConf();
		}
		return ConfSharePre;
	}

	public void updateDataRow_scan(String tablename, String english,
			int remembered_Times) {
		// TODO Auto-generated method stub
		remembered_Times++;
		String s = Ebbinghaus.getNextVisitDate(remembered_Times);
		String now = now();
		if (s != null)
			dbhelper.updateRow(tablename, english, remembered_Times, s, now);
		else
			dbhelper.gotIt(tablename, english);

	}

	public void unlock() {
		dbhelper.unlock(currentTable, today());
	}

	public void updateDataRow_gotit(String tablename, String english) {
		// TODO Auto-generated method stub
		dbhelper.gotIt(tablename, english);
	}

	public int getCount() {
		// TODO Auto-generated method stub
		return getConfSharePref().getInt(ConfKey.Count, -1);
	}

	public void setCount(int which) {
		// TODO Auto-generated method stub
		confhelper.put(ConfKey.Count, which);
	}

	
	/**
	 * 
	 * @return 
	 */
	public String getChEnStr() {
		// TODO Auto-generated method stub
		if(getChEn()==ConfValue.CE_CtoE)
			return "中译英";
		return "英译中";
	}
	public boolean getChEn(){
		return getConfSharePref().getBoolean(ConfKey.Mode_ChEn, true);
	}

	/**
	 * 
	 * @param b 
	 */
	public void setChEn(boolean b) {
		// TODO Auto-generated method stub
		confhelper.put(ConfKey.Mode_ChEn, b);
	}

	/**
	 * 
	 * @param which_temp
	 */
	public void setOrder(int which_temp) {
		// TODO Auto-generated method stub
		confhelper.put(ConfKey.Order, which_temp);
	}

	public List<ChoiceQuestion> getQuestions(String tablename, int studyNum) {
		currentTable = tablename;
		if (tablename.equals(RowEnglish.tablename)) {
			List<Row> rs = getTopRows(tablename, studyNum * 3, true);
			List<ChoiceQuestion> ques = new ArrayList<ChoiceQuestion>();
			if (getChEnStr().equals("中译英")) {
				for (int i = 0; i < studyNum; i++) {
					RowEnglish re = (RowEnglish) rs.get(i);
					RowEnglish re1 = (RowEnglish) rs.get(i + studyNum);
					RowEnglish re2 = (RowEnglish) rs.get(i + studyNum * 2);
					ques.add(new ChoiceQuestion(re.chinese, new String[] {
							re.english, re1.english, re2.english },
							re.Remembered_Times));
				}
			} else {
				for (int i = 0; i < studyNum; i++) {
					RowEnglish re = (RowEnglish) rs.get(i);
					RowEnglish re1 = (RowEnglish) rs.get(i + studyNum);
					RowEnglish re2 = (RowEnglish) rs.get(i + studyNum * 2);
					ques.add(new ChoiceQuestion(re.english, new String[] {
							re.chinese, re1.chinese, re2.chinese },
							re.Remembered_Times));
				}
			}
			return ques;
		}
		return null;
	}

	/**
	 * 
	 * @return
	 */
	public String getSwitchStr() {
		// TODO Auto-generated method stub
		if(ConfValue.switch_on==getSwitch())
				return "软件已开启";
		return "软件已关闭";
	}
	public boolean getSwitch(){
		return getConfSharePref().getBoolean(ConfKey.Switch, true);
	}

	/**
	 * 
	 * @param state
	 *            ConfValue.switch_off or switch_on
	 */
	public void setSwitch(boolean state) {
		confhelper.put(ConfKey.Switch, state);
	}

	/**
	 * @return 
	 */
	public boolean getModeNow() {
		getModeTime();
		int h = hour();
		if (scanTime[0] == 24)
			return ConfValue.Mode_Scan;
		else if (scanTime[0] == 0 && scanTime[1] == 0)
			return ConfValue.Mode_Ans;
		else {
			if (scanTime[0] < scanTime[1] && scanTime[0] < h && scanTime[1] > h)
				return ConfValue.Mode_Scan;
			else if (scanTime[0] > scanTime[1]
					&& (scanTime[0] < h || scanTime[1] > h))
				return ConfValue.Mode_Ans;
		}
		return ConfValue.Mode_Ans;
	}

	public void setModeTime(int[] scanTime) {
		// TODO Auto-generated method stub
		this.scanTime = scanTime;
		confhelper.put(ConfKey.ModeTime, scanTime[0] * 100 + scanTime[1]);
	}

	public int[] getModeTime() {
		if (scanTime[0] == -1) {
			int i = getConfSharePref().getInt(ConfKey.ModeTime, -1);
			scanTime[0] = i / 100;
			scanTime[1] = i % 100;
		}
		return scanTime;
	}
	
	public String[] getModeTimeStr(){
		scanTime = getModeTime();
		String[] str = {scanTime[0]+"",scanTime[1]+""};
		return str;
	}
	
	public String getCurrentResourceStr(){
		return Constants.resources.getResourceName(this.getCurrentResNum());
	}
	/**
	 * 获取当前资源在资源名与ID对中的位置（从0开始，非ID值）
	 * @return
	 */
	public int getCurrentResNum(){
		int resIDnum = confhelper.getCurrentResource();
		int i;
		for (i = 0; i < getLocalResPairs().length; i++) {
			if (getLocalResPairs()[i].getIdNum()==resIDnum) {
				break;
			}
		}
		return i;
	}

	/**
	 * 
	 * @param english
	 */
	public void updateDataRow_testWrong(String english) {
		// TODO Auto-generated method stub
		dbhelper.setRowTestWrong(currentTable, english);
	}
	public float getCurrentVision(){
		return confhelper.getCurrentVersion();
	}

	public String getOrderStr() {
		// TODO Auto-generated method stub
		switch(getOrder()){
		case ConfValue.order_normal%10:return "正序";
		case ConfValue.order_random%10:return "乱序";
		case ConfValue.order_reverse%10:return "逆序";
		}
		return null;
	}
	public int getOrder(){
		return confhelper.getOrder();
	}

	public String getSkinStr() {
		// TODO Auto-generated method stub
		switch(getSkin()){
		case ConfValue.Skin_Pink:return "玫瑰之恋";
		case ConfValue.Skin_Blue:return "蓝色星晴";
		}
		return null;
	}

	public int getSkin() {
		// TODO Auto-generated method stub
		return confhelper.getSkin();
	}

	private ResNameNumPair[] mUserDataNameNumPairs = null;
	public ResNameNumPair[] getLocalResPairs() {
		// TODO Auto-generated method stub
		if(mUserDataNameNumPairs==null)
			mUserDataNameNumPairs = dbhelper.getAllUserDataNameNumPair();
		return mUserDataNameNumPairs;
		 
	}

	public String[] getLocalResNames() {
		// TODO Auto-generated method stub
		ArrayList<String> strings = new ArrayList<String>();
		for (int i = 0; i < getLocalResPairs().length; i++) {
			strings.add(getLocalResPairs()[i].getResName());
		}
		return strings.toArray(new String[strings.size()]);
	}

	public void setCurrentResNum(int which) {
		// TODO Auto-generated method stub		
		int IDnum = getIDnum(which);
		confhelper.put(ConfKey.Current_Resource, IDnum);
	}

	/**
	 * 根据在NameNumPair中的序号，获取资源的IDnum值
	 * @param which
	 * @return
	 */
	private int getIDnum(int which) {
		// TODO Auto-generated method stub		
		return getLocalResPairs()[which].getIdNum();
	}

	public void setSkin(int which_temp) {
		// TODO Auto-generated method stub
		confhelper.put(ConfKey.Skin, which_temp);
	}	
}
